package cn.edu.xmu.oomall.order.dao;

import cn.edu.xmu.oomall.core.util.ReturnNo;
import cn.edu.xmu.oomall.core.util.ReturnObject;
import cn.edu.xmu.oomall.order.mapper.OrderItemPoMapper;
import cn.edu.xmu.oomall.order.model.bo.Order;
import cn.edu.xmu.oomall.order.model.bo.OrderItem;
import cn.edu.xmu.oomall.order.model.po.OrderItemPo;
import cn.edu.xmu.oomall.order.model.po.OrderItemPoExample;
import cn.edu.xmu.privilegegateway.annotation.util.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

import static cn.edu.xmu.privilegegateway.annotation.util.Common.cloneVo;

@Repository
public class OrderItemDao {
    @Autowired
    OrderItemPoMapper orderItemPoMapper;

    /**
     * 增加OrderItem
     */
    public ReturnObject insertOrderItem(OrderItem orderItem){
        OrderItemPo orderItemPo=cloneVo(orderItem,OrderItemPo.class);
        try{
            int ret=orderItemPoMapper.insert(orderItemPo);
            if(ret==0){
                return new ReturnObject(ReturnNo.FIELD_NOTVALID);
            }
            return new ReturnObject(orderItemPo);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR,e.getMessage());
        }
    }

    /**
     * 更新OrderItem
     */
    public ReturnObject updateOrderItem(OrderItem orderItem){
        OrderItemPo orderItemPo=cloneVo(orderItem,OrderItemPo.class);
        try{
            int ret=orderItemPoMapper.updateByPrimaryKey(orderItemPo);
            if(ret==0){
                return new ReturnObject(ReturnNo.FIELD_NOTVALID);
            }
            return new ReturnObject(orderItemPo);
        }catch (Exception e){
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR,e.getMessage());
        }
    }


    /**
     * 根据订单id查询OrderItems
     * @param orderId
     * @return
     */
    public ReturnObject selectOrderItemsByOrderId(Long orderId){
        OrderItemPoExample example=new OrderItemPoExample();
        OrderItemPoExample.Criteria criteria=example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        try{
            List<OrderItemPo> orderItemPos=orderItemPoMapper.selectByExample(example);
            List<OrderItem> orderItems=new ArrayList<>(orderItemPos.size());
            for(OrderItemPo orderItemPo:orderItemPos){
                OrderItem orderItem=cloneVo(orderItemPo,OrderItem.class);
                orderItems.add(orderItem);
            }
            return new ReturnObject(orderItems);
        }catch (Exception e){
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR,e.getMessage());
        }
    }


}
